package com.tianji.learning.mq;


import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static com.tianji.common.constants.MqConstants.Key.ORDER_REFUND_KEY;
import static com.tianji.common.constants.MqConstants.Queue.LEARNING_LESSON_PAY_QUEUE;
import static com.tianji.common.constants.MqConstants.Queue.LEARNING_LESSON_REFUND_QUEUE;

@Component
@Slf4j
@RequiredArgsConstructor
public class LessonChange {
    private final ILearningLessonService lessonService;

    /**
     * 1.监听订单支付消息->新增课程到用户的课表（Day2-> 课堂）
     * @param orderMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = LEARNING_LESSON_PAY_QUEUE, durable = "true"),
            exchange = @Exchange(value = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY))
    public void listenOrderPayMsg(OrderBasicDTO orderMsg){
        log.info("订单支付成功，开始处理课程信息");
        //键壮性检测
        if (ObjectUtil.isEmpty(orderMsg) || ObjectUtil.isEmpty(orderMsg.getUserId()) || ObjectUtil.isEmpty(orderMsg.getCourseIds())) {
       return;
        }

        //去业务层写代码
        lessonService.addLessons(orderMsg.getUserId(), orderMsg.getCourseIds());
    }



    /**
     * 1.监听订单支付消息->删除退费的信息（作业一）
     * @param orderMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = LEARNING_LESSON_REFUND_QUEUE, durable = "true"),
            exchange = @Exchange(value = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_REFUND_KEY))
    public void listenOrderRefundMsg(OrderBasicDTO orderMsg){
        log.info("订单取消成功，开始处理课程信息");
        //键壮性检测
        if (ObjectUtil.isEmpty(orderMsg) || ObjectUtil.isEmpty(orderMsg.getUserId()) || ObjectUtil.isEmpty(orderMsg.getCourseIds())) {
            return;
        }

        //去业务层写代码
        lessonService.removeLessons(orderMsg.getUserId(), orderMsg.getCourseIds());
    }


}
